package com.appkudos.view;
import java.util.List;

import com.appkudos.controller.UserController;
import com.appkudos.model.User;
import com.appkudos.view.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * specific login screen only for emulator
 * @author justineyang
 *
 */
public class LoginActivity extends Activity{
	Button signin;
	Spinner login_name;
	User user;
	UserController uc;
	private Activity PARENTACTIVITY;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // set the correct view 
        setContentView(R.layout.view_login); 
        
	    // instantiate user controller
	    uc = new UserController();
	    user = null;
	   
	    
        // initialize class variables
        PARENTACTIVITY = this;
        login_name = (Spinner) findViewById(R.id.login_name);  
        signin = (Button) findViewById(R.id.login_button);
        
        // 
        signin.setOnClickListener(buttonListener);  
        
        // populate spinner with all users in the database
	    populateUsers();

    }
	
	// populate the user spinner with all the users from the database
	private void populateUsers(){
    	List<User> all_users = uc.getAllUsers();
    	
    	ArrayAdapter <CharSequence> adapter = new ArrayAdapter <CharSequence> (this, android.R.layout.simple_spinner_item);
    	adapter.add("Choose a user");
    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	for (int i=0; i<all_users.size(); i++){
    		adapter.add(all_users.get(i).getUsername());
    	}
    	
    	login_name.setAdapter(adapter); 
	}
	
    private OnClickListener spinnerListener = new OnClickListener() {
    	public void onClick(View v){
 		
    	}
    };
    
    private OnClickListener buttonListener = new OnClickListener() {
    	public void onClick(View v){
	    	  // get the selected user from db
	    	  int selected_position = login_name.getSelectedItemPosition();
	          String selected_user = login_name.getItemAtPosition(selected_position).toString();
	          if(selected_user == "")
	        	  selected_user = "Tiff";
	          user = uc.getUserProfile(selected_user);   
	    		
	  	      //Verify if it's a real user
	  	      if (user == null){
	  	    	  Toast.makeText(getApplicationContext(), "Username doesn't exist",Toast.LENGTH_SHORT).show();
	  	      }else{             	          
	  		      // start the application
	  		      Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
	  		      intent = uc.passCurrentUser(intent, user);
	  	  		  startActivity(intent);
	  	  		finish();
	  	      }	 		
    	}
    };
}

